package com.lu.manage.modular.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.manage.core.common.constant.SystemConstant;
import com.lu.manage.core.common.exception.SysLogExcepetion;
import com.lu.manage.core.common.node.TreeNodes;
import com.lu.manage.core.tips.SuccessTip;
import com.lu.manage.core.utils.ToolUtil;
import com.lu.manage.modular.system.mapper.DictTypeMapper;
import com.lu.manage.modular.system.model.Dict;
import com.lu.manage.modular.system.model.DictType;
import com.lu.manage.modular.system.service.DictService;
import com.lu.manage.modular.system.service.DictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Project LuBoot
 * @Author: zhanglu
 * @Date: 2019-11-17 00:46:19
 * @Description: 字典类型表 服务实现类
 */
@Service
public class DictTypeServiceImpl extends ServiceImpl<DictTypeMapper, DictType> implements DictTypeService {

    @Autowired
    private DictService dictService;

    @Override
    public Object listPage(Map<String, Object> map) throws SysLogExcepetion {
        SuccessTip successTip = new SuccessTip();
        try {
            Page page = new Page(Integer.valueOf((String)map.get(SystemConstant.PAGE)), Integer.valueOf((String)map.get(SystemConstant.LIMIT)));
            QueryWrapper queryWrapper = new QueryWrapper();
            map.forEach((k, v) -> {
                if(!k.equals(SystemConstant.PAGE) && !k.equals(SystemConstant.LIMIT)){
                    if(k.equals(SystemConstant.SEARCH_WORDS)){
                        queryWrapper.like("name", v);
                    }else {
                        queryWrapper.eq(k, v);
                    }
                }
            });
            queryWrapper.orderByAsc("sort");
            IPage<DictType> dictTypeList = this.baseMapper.selectPage(page, queryWrapper);
            successTip.setCount(dictTypeList.getTotal());
            successTip.setData(dictTypeList.getRecords());
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
        return successTip;
    }

    @Override
    public Object list(Map<String, Object> map) throws SysLogExcepetion {
        List<DictType> dictTypeList = new ArrayList<>();
        try {
            QueryWrapper<DictType> queryWrapper = new QueryWrapper<>();
            if(ToolUtil.isNotEmpty(map)){
                map.forEach((k, v) -> {
                    queryWrapper.eq(k, v);
                });
            }
            dictTypeList = this.baseMapper.selectList(queryWrapper);
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
        return dictTypeList;
    }

    @Override
    public Object addObj(DictType dictType) throws SysLogExcepetion {
        try {
            return this.baseMapper.insert(dictType);
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
    }

    @Override
    public Object updateObj(DictType dictType) throws SysLogExcepetion {
        try {
            return this.baseMapper.updateById(dictType);
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
    }

    @Override
    public Object deleteObj(String data) throws SysLogExcepetion {
        try {
            List<DictType> dictTypeList = JSONArray.parseArray(data, DictType.class);
            List<String> ids = dictTypeList.stream().map(DictType::getId).collect(Collectors.toList());
            return this.baseMapper.deleteBatchIds(ids);
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
    }

    @Override
    public Object dictTypeTreeList() {
        return this.baseMapper.dictTypeTreeList();
    }

    @Override
    public void sortAllDictTypes(String nodes) {
        List<TreeNodes> nodesList = JSONArray.parseArray(nodes, TreeNodes.class);
        System.out.println(nodes);
        for (TreeNodes node : nodesList) {
            handle( node);
        }
        sortIndex = 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateState(String id, Integer state) {
        //修改本表
        DictType dictType = new DictType();
        dictType.setId(id);
        dictType.setState(state);
        this.updateById(dictType);

        //修改子表相关联的状态
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.set("dict_type_id", id);
        Dict dict = new Dict();
        dict.setState(state);
        dictService.update(dict, updateWrapper);

    }


    public static int sortIndex = 0;

    public void handle(TreeNodes treeNodes){
        for (TreeNodes n : treeNodes.getChildren()) {
            if(ToolUtil.isNotEmpty(n.getId()) && !n.getId().equals(SystemConstant.pid)){
                if(ToolUtil.isEmpty(n.getChildren())){
                    DictType dictType = new DictType();
                    dictType.setId(n.getId());
                    dictType.setSort(sortIndex);
                    sortIndex++;
                    this.baseMapper.updateById(dictType);
                }else {
                    DictType dictType = new DictType();
                    dictType.setId(n.getId());
                    dictType.setSort(sortIndex);
                    sortIndex++;
                    this.baseMapper.updateById(dictType);
                    handle(n);
                }
            }
        }
    }

}
